package com.yangrong.thread.chapter9;

import java.util.Optional;
import java.util.stream.Stream;

import com.yangrong.thread.chapter9.Lock.TimeOutException;

public class LockTest {

	public static void main(String[] args) {
		final BooleanLock booleanLock = new BooleanLock();
		Stream.of("T1", "T2", "T3", "T4").forEach(name -> new Thread(() -> {
			try {
				booleanLock.lock(1000);
				Optional.of(Thread.currentThread().getName() + " have the lock Monitor.")
						.ifPresent(System.out::println);
				work();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (TimeOutException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
				booleanLock.unlock();
			}
		}, name).start());
	}

	private static void work() {
		Optional.of(Thread.currentThread().getName() + " is Working...").ifPresent(System.out::println);
		try {
			Thread.sleep(10_000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
